package com.company.controller;

import com.company.mapper.EmployeeMapper;
import com.company.model.Employee;
import com.company.model.User;
import com.company.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/employee/add")
public class AddEmployeeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/jsp/employee/add.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        // 1. 获取表单数据（同之前逻辑）
        Employee employee = new Employee();
        employee.setName(request.getParameter("name"));
        employee.setDepartment(request.getParameter("department"));
        employee.setPosition(request.getParameter("position"));
        employee.setSalary(new BigDecimal(request.getParameter("salary")));
        employee.setEmail(request.getParameter("email"));
        employee.setPhone(request.getParameter("phone"));
        try {
            employee.setHireDate(new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("hireDate")));
        } catch (ParseException e) {
            request.setAttribute("error", "日期格式错误");
            request.getRequestDispatcher("/WEB-INF/jsp/employee/add.jsp").forward(request, response);
            return;
        }
        // 获取当前登录用户ID
        HttpSession session = request.getSession();
        employee.setCreatedBy(((User) session.getAttribute("user")).getId());

        // 2. 调用MyBatis添加
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
        employeeMapper.addEmployee(employee);
        MyBatisUtil.closeSqlSession(sqlSession);

        // 3. 跳转列表页
        response.sendRedirect(request.getContextPath() + "/employee/list?message=添加成功");
    }
}